package ntd.util.frame.action.ai;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.modular.extra.ai.FactoryAiOpt;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.javacv.tool.ToolAiUserSites;

import java.sql.SQLException;
import java.util.List;

public class ActionAiStatisticsType extends ActionAbs {

    @Override
    public ActionInfo info() {
        return new ActionInfo("AI统计-按类型统计", "ai-statistics-type", new ActionAiStatisticsType());
    }

    @Override
    public ActionOutBo handle() {
        

        String mn = actionInBo.getParamStr("mn");

        //数据库
        Db use = Db.use(FactoryData.dataSource("272ab1b9c5cc4ea2b76302238247284c"));

        String whereSql = "where 1 = 1";
        if (StrUtil.isNotBlank(mn)) {

            if (!ToolAiUserSites.IsExistMn(mn)){
                throw new ComException("没有该站点的权限，请联系管理员！");
            }

            whereSql += StrUtil.format(" and siteMn = '{}'", mn);
        }

        String sql = "select count(*) as num, ai_mode_type from airesult " + whereSql + " group by ai_mode_type";

        try {
            List<Entity> entities = use.query(sql);


            List<JSONObject> jsonObjects = CollStreamUtil.toList(FactoryAiOpt.OPT_VISION_MODEL.cacheListAll(), visionModelDo -> {
                Entity entityItem = CollectionUtil.findOne(entities, entity -> entity.getStr("ai_mode_type").equals(visionModelDo.getCode()));
                JSONObject jsonObject = new JSONObject();
                jsonObject.putOpt("name", visionModelDo.getName());
                jsonObject.putOpt("num", ObjectUtil.isNull(entityItem) ? 0 : entityItem.getInt("num"));
                jsonObject.putOpt("code", visionModelDo.getName());
                return jsonObject;
            });

            return new ActionOutBo(jsonObjects);
        } catch (SQLException e) {
            StaticLog.error(e, "[AI][分类查询][{}]失败...");
            throw new ComException("分类查询失败，请稍后重试...");
        }
    }
}
